// pages/login/login.js
let app = getApp()
// 获取云数据库引用
const db = wx.cloud.database()
const admin = db.collection('adminlist')
const MAX_LIMIT = 20
let username = ''
let password = ''

Page({

  /**
   * 页面的初始数据
   */
  data: {
    adminList: [],
    switchChecked: true,
    username: '',
    password: ''
  },

  // 输入用户名
  inputName: function (event) {
    username = event.detail
    this.setData({
      username: event.detail
    })
  },
  // 输入密码
  inputPassword (event) {
    password = event.detail
    this.setData({
      password: event.detail
    })
  },

  // 记住密码开关
  switchChange: function (event) {
    // 得到值
    let checkedValue = event.detail.value
    let that = this
    if (checkedValue) {
      that.setData({
        switchChecked: true
      })
    } else {
      that.setData({
        switchChecked: false
      })
    }
  },

  // 找回密码
  recoverPwd: function () {
    wx.navigateTo({
      url: '/pages/recoverPwd/recoverPwd'
    })
  },

  // 找回用户名
  recoverUn: function () {
    wx.navigateTo({
      url: '/pages/recoverUn/recoverUn'
    })
  },

  // 登录
  login () {
    let that = this
    let checkedValue = that.data.switchChecked
    // 登陆获取用户信息
    if (username === '') {
      wx.showToast({
        title: '请输入用户名',
        icon: 'error',
        duration: 2500
      })
    } else {
      admin.count().then(async (res) => {
        let total = res.total
        // 计算需分几次取
        const batchTimes = Math.ceil(total / MAX_LIMIT)
        let newData
        let oldData
        // 承载所有读操作的 promise 的数组
        for (let i = 0; i < batchTimes; i++) {
          await admin.skip(i * MAX_LIMIT).limit(MAX_LIMIT)
            .get()
            .then(async (res) => {
              newData = res.data
              oldData = that.data.adminList
              that.setData({
                adminList: oldData.concat(newData)
              })
            })
        }
      })
        .then((res) => {
          let user = that.data.adminList
          let flag = false
          for (let i = 0; i < user.length; i++) { // 遍历数据库对象集合
            if (username === user[i].username) {
              flag = true // 用户名存在
              if (password !== user[i].password) { // 判断密码是否正确
                wx.showToast({
                  title: '密码错误！',
                  icon: 'error',
                  duration: 2500
                })
              } else {
                if (checkedValue) { // 如果记住密码则向微信缓存写入账号密码
                  wx.setStorageSync('username', that.data.username)
                  wx.setStorageSync('password', that.data.password)
                } else { // 如果不记住密码则清空微信缓存存在的账号密码
                  wx.setStorageSync('username', '')
                  wx.setStorageSync('password', '')
                }
                console.log('登录成功！')
                wx.switchTab({ // 跳转首页
                  url: '/pages/index/index'
                })
                wx.setStorageSync('loginMsg', JSON.stringify(user[i]))
                wx.showToast({
                  title: '登录成功！',
                  icon: 'success',
                  duration: 2500
                })
              }
            }
          }
          if (!flag) {
            wx.showToast({
              title: '无此用户名！',
              icon: 'error',
              duration: 2500
            })
          }
        })
    }
  },

  // 注册
  register () {
    wx.navigateTo({
      url: '/pages/register/register'
    })
  },


  /**
   * 生命周期函数--监听页面加载
   *
   */
  onLoad: function (options) {
    let that = this
    // 页面加载时，从微信缓存读取账号密码
    that.setData({
      username: wx.getStorageSync('username'),
      password: wx.getStorageSync('password')
    })
    username = that.data.username
    password = that.data.password
  }

})